package com.core.family.admin.Interceptor;

import cn.hutool.json.JSONUtil;
import com.core.common.cons.RespCode;
import com.core.common.domain.response.R;
import com.core.common.utils.JwtUtil;
import com.core.family.admin.config.AuthProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: kuntail
 * @description:
 * @author: honglei
 * @create: 2022-03-31 14:14
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    AuthProperties authProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        StringBuffer urL = request.getRequestURL();
        String uri = request.getRequestURI();
        for (String s : authProperties.getSkipurls()) {
            if (uri.contains(s)) {
                return true;
            }
        }
        if (true){
            return  true;
        }

        String token = request.getHeader(authProperties.getTokenName());

        if (!StringUtils.isEmpty(token) && JwtUtil.validateToken(token)) {
            UserUtil.setUserInfo(token);
            return true;
        }

        String json = JSONUtil.toJsonStr(R.error(RespCode.UNLOGIN));
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.getWriter().write(json);
        return false;

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }
}
